/*
 * @Author: yjp
 * @Date: 2022-03-10 14:46:47
 */
import React from 'react';
import Keycloak from 'keycloak-js';
import type {RequestConfig, RunTimeLayoutConfig} from 'umi';
import {ReactKeycloakProvider} from '@react-keycloak/web';
import {API_PERFIX} from './constant';
import UserMenu from './compoments/UserMenu';
import {PageLoading} from '@ant-design/pro-layout';

const keycloak = Keycloak({
  'realm': 'dev',
  'url': 'http://keycloak.lixulife.com/auth',
  'clientId': 'megalab',
});


export async function getInitialState() {
  return {};
}

export const layout: RunTimeLayoutConfig = ({initialState}: any) => {
  return {
    rightContentRender: () => <UserMenu/>,
    ...initialState?.settings,
  };
};

export function rootContainer(container: React.ReactNode) {
  return React.createElement(ReactKeycloakProvider, {
    authClient: keycloak,
    initOptions: {
      onLoad: 'login-required',
      checkLoginIframe: false,
      enableLogging: true,
      isLoadingCheck: true
    },
    onEvent: (event) => {
      if (event === 'onTokenExpired') {
        keycloak.logout();
        return;
      }
    }
  }, container);
}

export const request: RequestConfig = {
  timeout: 10000,
  credentials: 'include',
  errorConfig: {},
  requestInterceptors: [(url, options) => {
    const {headers = {}} = options;
    return {
      url: `${API_PERFIX}${url}`,
      options: {
        ...options,
        headers: {
          token: keycloak.token || '',
          ...headers
        },
        interceptors: true
      },
    };
  }],
  responseInterceptors: [],
};

export const initialStateConfig = {
  loading: <PageLoading/>,
};
